from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework import status
# 处理关于数据库异常的导包
# from django.db import DatabaseError


def exception_handler(exc, context):
    # drf自带的异常处理
    # 先调用REST framework默认的异常处理方法获得标准错误响应对象
    response = drf_exception_handler(exc, context)

    # resonse 为None说明drf未处理该异常
    # 在此处补充自定义的异常处理
    if response is None:
        view = context['view']
        # 判断异常类型
        if isinstance(exc, ZeroDivisionError):
            print('[%s]: %s' % (view, exc))
            response = Response({'detail': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

    return response
